package com.captjack.sort;

import java.util.Arrays;

import static com.captjack.sort.SimpleSort.swap;

/**
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2022/10/11 12:26
 * package com.captjack.docker.simple.application
 */
public class QuickSort {

    /**
     * 1、三路快排优化重复元素过多问题
     * 2、随机选取基准元素避免退化为冒泡排序
     *
     * @param args
     */
    public static void main(String[] args) {
        int[] nums = {11, 24, 5, 32, 50, 34, 54, 76};
        System.out.println("快速排序前:" + Arrays.toString(nums));
        int[] temp = new int[8];
        quickSort(nums, 0, nums.length - 1);
        System.out.println("快速排序后:" + Arrays.toString(nums));
    }

    public static void quickSort(int[] arr, int left, int right) {
        if (left < right) {
            int part = partition(arr, left, right);
            quickSort(arr, left, part - 1);
            quickSort(arr, part + 1, right);
        }
    }

    public static int partition(int[] arr, int left, int right) {
        // 可以随机选取优化，避免快排退化
        int pivot = arr[left], key = left;
        while (left < right) {
            while (left < right && arr[right] >= pivot) {
                right--;
            }
            while (left < right && arr[left] <= pivot) {
                left++;
            }
            swap(arr, left, right);
        }
        swap(arr, left, key);
        return left;
    }

}
